from datetime import datetime
import json
import os
import platform
import uuid
import json
from dataclasses import dataclass, asdict


@dataclass
class Result:
    code: str
    msg: str
    data: object

    def to_json(self):
        return json.dumps(asdict(self), ensure_ascii=False)

    def to_dic(self):
        return asdict(self)


# 返回结果转换,Dic
def dic_result(code, msg, data, reDic=True):
    result = Result(code, msg, data)
    if reDic:
        return result.to_dic()
    else:
        return result.to_json()


# 生成uuid
def generate_uuid():
    return str(uuid.uuid4()).replace("-", "")


# 获取当前时间戳，精确到毫秒
def get_time_millisecond(isFormat=False):
    # 获取当前时间
    now = datetime.now()
    # 定义时间格式，包含毫秒，截取前 3 位毫秒数
    time_format = "%Y%m%d%H%M%S%f" #20251009181306829
    formatted_time = now.strftime(time_format)[:-3]
    # 格式化日期，
    if isFormat: #示例 2025-10-09 18:17:29
        formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")        
    # print(formatted_time)
    return formatted_time


# 字符串转int
def str_to_int(str_num, default_value=0):
    try:
        if str_num == "":
            return default_value
        return int(str_num)
    except ValueError:
        return default_value


# 获取文件的绝对路径
def get_abspath(filename):
    try:
        current_dir = os.getcwd()
        filename = os.path.normpath(os.path.join(current_dir, filename))
        return filename
    except Exception as e:
        print(f"获取文件绝对路径时出现错误: {e}")
        return ""


# 打开文件目录
def open_file_directory(path):
    system = platform.system()
    try:
        directory = os.getcwd()
        if os.path.exists(path):
            directory = path
        if system == "Windows":
            os.startfile(directory)
        elif system == "Darwin":  # macOS
            os.system(f'open "{directory}"')
        elif system == "Linux":
            os.system(f'xdg-open "{directory}"')
        else:
            print("不支持的操作系统")
    except:
        # 获取当前工作目录（可能与脚本目录不同）
        current_dir = os.getcwd()
        os.startfile(current_dir)

    # 获取日期串(毫秒)，


# 删除指定目录下的文件
def del_temp_files():
    try:

        def delete_files_in_directory(directory_path):
            for root, dirs, files in os.walk(directory_path):
                for file in files:
                    file_path = os.path.join(root, file)
                    try:
                        os.remove(file_path)  # 删除文件
                        print(f"已删除文件：{file_path}")
                    except Exception as e:
                        print(f"删除文件 {file_path} 时出错：{e}")

        # 设置需要清理的目录列表
        directories_to_clean = ["logs"]
        # 遍历每个目录并删除其中的文件
        for directory in directories_to_clean:
            if os.path.exists(directory) and os.path.isdir(directory):
                delete_files_in_directory(directory)
                print(f"目录 '{directory}' 下的所有文件已删除。")
            else:
                print(f"目录 '{directory}' 不存在或不是一个有效的目录。")

    except Exception as e:
        print(f"删除临时文件时出现错误: {str(e)}")


if __name__ == "__main__":
    """
    测试代码
    """
    res = get_time_millisecond(True)
    print(res)
